package org.pub.fast.jdbc.cross.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SqlHistoryMap {
	public static final String KEY = "sqlHistoryMap";

	private Map<Integer, SqlHistory> historyMap = new HashMap<Integer, SqlHistory>();

	private static Map<Thread, Map<String, Object>> threadStateMap = new HashMap<Thread, Map<String, Object>>();
	
	public SqlHistory getSqlHistory(int conn) {
		return historyMap.get(conn);
	}

	public void addSqlHistory(SqlHistory history) {
		historyMap.put(history.getConnId(), history);
	}

	public static SqlHistoryMap getCurrentSqlHistoryMap() {
		SqlHistoryMap sqlHistoryMap = (SqlHistoryMap)getMappedThreadState(SqlHistoryMap.KEY);
		if (sqlHistoryMap == null) {
			sqlHistoryMap = new SqlHistoryMap();
		}

		return sqlHistoryMap;
	}

	@SuppressWarnings("unchecked")
	public static SqlHistory[] getAllSqlHistory() {
		List historyMapList = getMappedThreadStates(KEY);
		List l = new ArrayList();
		for (Object o : historyMapList) {
			l.addAll(((SqlHistoryMap) o).historyMap.values());
		}
		return (SqlHistory[]) l.toArray(new SqlHistory[0]);

	}
	
	public static Object getMappedThreadState(String key) {
		return getMappedThreadState(Thread.currentThread(), key);
	}

	
	@SuppressWarnings("unchecked")
	public static List getMappedThreadStates(String key) {
		List list = new ArrayList();
		Set<Thread> threadStateKeys = threadStateMap.keySet();
		for (Thread t : threadStateKeys) {
			Object o = getMappedThreadState(t, key);
			if (o != null) {
				list.add(o);
			}
		}
		return list;
	}

	public static void setMappedThreadState(String key, Object value) {
		Map<String, Object> map = threadStateMap.get(Thread.currentThread());
		if (map == null) {
			map = new HashMap<String, Object>();
			threadStateMap.put(Thread.currentThread(), map);
		}

		map.put(key, value);
	}
	
	public static Object getMappedThreadState(Thread thread, String key) {
		Map<String, Object> map = null;
		synchronized (threadStateMap) {
			map = threadStateMap.get(thread);
		}
		if (map != null) {
			return map.get(key);
		} else {
			return null;
		}
	}

}
